from fastapi import APIRouter, Request
from src.constants.resultcode import ResultCode
from src.schemas.draft import DraftDataResponse, DraftRequest, DraftData,DraftQueryRequest, DraftSaveRequest
from src.service.save_draft import query_script, save_draft_impl
from src.utils.response import ApiResponse, ResponseModel
from src.service.create_draft import create_draft
from src.utils import helper
from .base import RouterMeta
from src.utils.logger import get_logger

import json

logger = get_logger("capcut")
router = APIRouter()

@router.post("/create_draft",response_model=DraftDataResponse, name="创建草稿")
async def create_draft_data(request: Request, draft_request: DraftRequest):
    """
    草稿创建
    """
    try:
        script, draft_id = create_draft(
            width=draft_request.width,
            height=draft_request.height
        )
        draft_data = DraftData(
            draft_id=draft_id,
            draft_url=helper.generate_draft_url(draft_id)
        )
        return ApiResponse.success(
            data=draft_data,
            message="草稿创建成功"
        )
    except Exception as e:
        logger.error(f"创建草稿失败: {str(e)}", exc_info=True)
        return ApiResponse.error(
            result_code=ResultCode.ERROR,
            message=f"创建草稿失败: {str(e)}",
        )

@router.post("/query_draft",response_model=ResponseModel ,name="查询草稿")
async def query_draft(request: Request, query_request: DraftQueryRequest):
    """
    草稿查询——配合客户端下载
    """
    try:
        script = query_script(query_request.draft_id ,query_request.force_update)
        if script:
            script_dict = json.loads(script.dumps())
            return ApiResponse.success(
                data={"script":script_dict},
            )
        return ApiResponse.error(
            result_code=ResultCode.ERROR,
            message="查询草稿失败: 草稿不存在",
        )
    except Exception as e:
        logger.error(f"查询草稿失败: {str(e)}", exc_info=True)
        return ApiResponse.error(
            result_code=ResultCode.ERROR,
            message=f"查询草稿失败: {str(e)}",
        )

@router.post("/save_draft",response_model=ResponseModel ,name="保存草稿并导出")
async def save_draft(request: Request, draft_save: DraftSaveRequest):
    """
    保存草稿——服务端直接打包返回链接
    """
    try:
        draft_result = save_draft_impl(draft_save.draft_id ,draft_save.draft_dir,True)
        return ApiResponse.success(
            data=draft_result,
        )
    except Exception as e:
        logger.error(f"保存草稿并导出异常: {str(e)}", exc_info=True)
        return ApiResponse.error(
            result_code=ResultCode.ERROR,
            message=f"保存草稿并导出异常: {str(e)}",
        )

meta = RouterMeta(
    router=router,
    prefix="/draft",
    tags=["草稿"]
    # dependencies=AUTH_DEPENDENCIES
)